package com.usfot;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * Created by liyanxin on 2015/3/18.
 */
public class ZookeeperDemo3 {

    private static String ROOT = "/app";

    public static void main(String args[]) throws IOException, KeeperException, InterruptedException {

        ZooKeeper zk = new ZooKeeper("127.0.0.1:2181", 300000, new Watcher() {
            // 监控所有被触发的事件
            public void process(WatchedEvent event) {
                System.out.println("状态:" + event.getState() + "|类型:" + event.getType() +
                        "|Wrapper:" + event.getWrapper() + "|Path:" + event.getPath());
            }
        });

        // 创建一个目录节点
        zk.create(ROOT, "app".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT);
        for (int i = 0; i < 10; i++) {
            ByteBuffer b = ByteBuffer.allocate(4);
            byte[] value;

            // Add child with value i
            b.putInt(i);
            value = b.array();
            zk.create(ROOT + "/element", value, ZooDefs.Ids.OPEN_ACL_UNSAFE,
                    CreateMode.PERSISTENT_SEQUENTIAL);
        }
        zk.close();

    }
}
